<template>
  <div class="food-list-container">
    <!-- 食物列表 -->
    <van-list
        v-model:loading="loading"
        :finished="finished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="onLoad"
    >
      <van-cell-group inset>
        <van-cell
            v-for="food in foodList"
            :key="food.foodId"
            :title="food.foodName"
            :label="`${food.calorie} 千卡/100克`"
            is-link
            @click="goToDetail(food)"
            class="food-cell"
        >
          <!-- 自定义左侧图标 -->
          <template #icon>
            <van-image
                :src="food.image"
                width="40"
                height="40"
                round
                fit="cover"
                class="fruit-icon"
            />
          </template>

          <!-- 自定义右侧内容 -->
          <template #right-icon>
            <van-tag
                :type="getCalorieTagType(food.calorie)"
                size="mini"
                class="calorie-tag"
            >
              {{ getCalorieLevel(food.calorie) }}
            </van-tag>
          </template>
        </van-cell>
      </van-cell-group>
    </van-list>

    <!-- 空状态提示 -->
    <div v-if="foodList.length === 0 && !loading" class="empty-state">
      <van-empty image="search" description="暂无相关食物数据" />
    </div>

    <!-- 加载提示 -->
    <div v-if="loadingMore" class="loading-more">
      <van-loading size="16px">加载中...</van-loading>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/utils/axios';
import {
  List as VanList,
  CellGroup as VanCellGroup,
  Cell as VanCell,
  Image as VanImage,
  Tag as VanTag,
  Loading as VanLoading,
  Empty as VanEmpty
} from 'vant';

const router = useRouter()

// 接收父组件传递的keyword参数
const props = defineProps({
  keyword: {
    type: String,
    required: true
  }
})

// 响应式数据
const loading = ref(false)
const finished = ref(false)
const loadingMore = ref(false)
const foodList = ref([])

// 监听keyword变化
watch(() => props.keyword, (newKeyword) => {
  if (newKeyword) {
    searchFoods(newKeyword)
  }
})

// 搜索食物方法
const searchFoods = async (keyword) => {
  loading.value = true
  finished.value = false

  try {
    const response = await axios.get('/api/food/getByKeyWord', {
      params: { keyWord: keyword }
    })

    foodList.value = response.data || []

    // 无论数据多少条，都标记为已完成加载
    finished.value = true

    console.log('搜索结果:', foodList.value.length, '条数据')
  } catch (error) {
    console.error('搜索失败:', error)
    foodList.value = []
    finished.value = true
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// van-list的load事件
const onLoad = () => {
  // 这里可以用于分页加载，但根据需求，我们一次性加载所有数据
  // 所以直接标记为完成
  finished.value = true
}

const goToDetail = (food) => {
  router.push({
    name: 'FoodDetail',
    params: { id: food.id },
    query: { name: food.name }
  })
}

const getCalorieLevel = (calorie) => {
  const num = parseInt(calorie)
  if (num <= 35) return '极低'
  if (num <= 55) return '低等'
  if (num <= 75) return '中等'
  return '较高'
}

const getCalorieTagType = (calorie) => {
  const num = parseInt(calorie)
  if (num <= 35) return 'success'
  if (num <= 45) return 'success'
  if (num <= 55) return 'warning'
  return 'danger'
}

// 初始化加载
onMounted(() => {
  if (props.keyword) {
    searchFoods(props.keyword)
  }
})
</script>

<style scoped>
.food-list-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding: 12px;
}

.food-cell {
  margin-bottom: 8px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.fruit-icon {
  margin-right: 12px;
  border: 1px solid #f0f0f0;
}

.calorie-tag {
  margin-left: 8px;
}

.loading-more {
  text-align: center;
  padding: 16px;
  color: #969799;
}

.empty-state {
  padding: 40px 0;
}

:deep(.van-cell__title) {
  font-weight: 500;
  font-size: 16px;
  color: #333;
}

:deep(.van-cell__label) {
  color: #ff4444;
  font-weight: 600;
  font-size: 14px;
  margin-top: 4px;
}

:deep(.van-cell__value) {
  color: #969799;
  font-size: 12px;
}

:deep(.van-cell-group--inset) {
  margin: 0;
}

:deep(.van-list__finished-text) {
  padding: 16px;
  color: #969799;
  font-size: 14px;
}
</style>